using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SQLitenSupport.Data;

namespace SQLitenSupport.UI
{

    /// <summary>
    /// 
    /// </summary>
    public partial class CreateTable : Form
    {

        #region Events & Objects

        // Event
        public delegate void DialogFinished( string tableName );
        public event DialogFinished DialogDisposed;

        public delegate void DialogUndone();
        public event DialogUndone DialogCancelled; 

        // DataTable to hold Schema
        private DataTable Schema;

        // DB Transactions object
        private SQLTransactions DBTransactions = null;

        #endregion

        #region Class Constants & Variables

        // Database Name
        private string _DatabaseName;

        // Saved Flag
        private bool Saved = true;

        #endregion

        #region Constructor(s)

        /// <summary>
        /// 
        /// </summary>
        /// <param name="databaseName"></param>
        public CreateTable( string databaseName )
        {

            // Main Init Routine
            InitializeComponent();

            // Set database
            this._DatabaseName = databaseName;

            // Extract just filename from full path
            int count = databaseName.Length;
            while (databaseName[count - 1] != '\\')
                count--;

            // Set caption
            this.Text = "Create new Table in '" + databaseName.Substring( count ) + "'";

            // Instantiate DataTable
            InitDataTable();

        } 

        #endregion

        #region Button-Click Event Handlers

        // Create table clicked
        private void btnCreate_Click( object sender, EventArgs e )
        {

            // ---------------------------------------------------------------
            //                      Primary Checks
            // ---------------------------------------------------------------
            if (txtTableName.Text.Length == 0)
            {

                // Show error
                MessageBox.Show( "You haven't entered a table name. Cannot save a table without a name.",
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );

                // Exit
                return;


            } // if

            // Check if the DataTable has any rows
            if (dgvTable.Rows.Count == 0)
            {

                // Show error
                MessageBox.Show( "You haven't created any fields. Cannot save a blank table.",
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );

                // Exit
                return;

            } // if

            // ---------------------------------------------------------------
            //                      Table creation method
            // ---------------------------------------------------------------
            // Clear the DataTable first
            Schema.Rows.Clear();

            // Loop and populate data table
            for (int count = 0; count < dgvTable.Rows.Count; count++)
            {

                if (dgvTable.Rows[count].Cells[0].Value != null &&
                     dgvTable.Rows[count].Cells[1].Value != null)
                {

                    // Create new row
                    DataRow schemaRow = Schema.NewRow();

                    schemaRow[0] = dgvTable.Rows[count].Cells[0].Value;
                    
                    schemaRow[1] = dgvTable.Rows[count].Cells[1].Value;
                    
                    if (dgvTable.Rows[count].Cells[2].Value != null)
                        schemaRow[2] = dgvTable.Rows[count].Cells[2].Value;
                    else
                        schemaRow[2] = "";

                    if (dgvTable.Rows[count].Cells[3] == null)
                        schemaRow[3] = false;

                    if (dgvTable.Rows[count].Cells[4] == null)
                        schemaRow[4] = false;

                    if (dgvTable.Rows[count].Cells[5] == null)
                        schemaRow[5] = false;

                    // Add the row
                    Schema.Rows.Add( schemaRow );

                } // end if

            } // end for

            // Init new DB Transactor
            DBTransactions = new SQLTransactions();

            // Connection & Query Strings
            DBTransactions.ConnectionString = "Data Source=" + _DatabaseName;

            // See if table was created successfully
            if (DBTransactions.CreateTable( Schema, txtTableName.Text ) == SQLStatus.CreateTableSuccess)
            {

                // Show success message
                MessageBox.Show( "Table " + txtTableName.Text + " created.", "Success",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information );

                // Nullify connector
                if (DBTransactions != null)
                {

                    DBTransactions.Dispose();
                    DBTransactions = null;

                } // if

                // Dispose this
                this.Dispose();

                // Raise event
                if (DialogDisposed != null)
                    DialogDisposed( txtTableName.Text );

            } // if
            else
            {

                // Show error message
                MessageBox.Show( " Table creation failure", "",
                            MessageBoxButtons.OK, MessageBoxIcon.Error );

            } // else

        }

        // Cancel clicked
        private void btnCancel_Click( object sender, EventArgs e )
        {

            // If not Saved
            if (!Saved)
            {

                // Ask for user confirmation before quitting
                if (MessageBox.Show( "You've unsaved table data. Discard changes?",
                        "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) == DialogResult.No)
                    return;

            }

            // Dispose myself
            this.Dispose( true );

            // Raise event
            if (DialogCancelled != null)
                DialogCancelled();

        }

        #endregion

        #region DataTable Initialization Method(s)

        // Init the Data Table
        private void InitDataTable()
        {

            // Instantiate DataTable
            Schema = new DataTable( "Schema" );

            // Add columns
            DataColumn dtcField = new DataColumn( "Field Name", System.Type.GetType( "System.String" ) );
            DataColumn dtcType = new DataColumn( "Data Type", System.Type.GetType( "System.String" ) );
            DataColumn dtcDefault = new DataColumn( "Default", System.Type.GetType( "System.String" ) );
            DataColumn dtcPrimary = new DataColumn( "Primary Key", System.Type.GetType( "System.Boolean" ) );
            DataColumn dtcBinary = new DataColumn( "Binary", System.Type.GetType( "System.Boolean" ) );
            DataColumn dtcNull = new DataColumn( "Not Null", System.Type.GetType( "System.Boolean" ) );
            Schema.Columns.AddRange(

                new DataColumn[] 
                {

                    dtcField, 
                    dtcType, 
                    dtcDefault, 
                    dtcPrimary, 
                    dtcBinary, 
                    dtcNull 

                } );

        }

        #endregion

    } // class

} // namespace